package com.zy.fee.roadpark.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import com.flyco.roundview.RoundLinearLayout;
import com.flyco.roundview.RoundRelativeLayout;
import com.spd.print.jx.constant.ParamsConstant;
import com.spd.print.jx.inter.IConnectCallback;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.activity.nb.FaultDeclareActivity;
import com.zy.fee.roadpark.activity.nb.MessageListActivity;
import com.zy.fee.roadpark.activity.nb.NbPayBackListActivity;
import com.zy.fee.roadpark.activity.nb.NbReceivablesActivity;
import com.zy.fee.roadpark.activity.nb.NbRegistrationPlateActivity;
import com.zy.fee.roadpark.activity.nb.NbSpotListActivity;
import com.zy.fee.roadpark.activity.np.LeaveApplyActivity;
import com.zy.fee.roadpark.activity.np.NpPayBackListActivity;
import com.zy.fee.roadpark.activity.np.NpRegistrationPlateActivity;
import com.zy.fee.roadpark.activity.np.NpSpotListActivity;
import com.zy.fee.roadpark.activity.np.PlateFindActivity;
import com.zy.fee.roadpark.app.AppApplication;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.CommonLogic;
import com.zy.fee.roadpark.dao.NpNodeLogic;
import com.zy.fee.roadpark.dao.NpNodeRecordLogic;
import com.zy.fee.roadpark.model.M_Lot;
import com.zy.fee.roadpark.model.apimodel.APIM_AdminInfo;
import com.zy.fee.roadpark.model.apimodel.APIM_LotList;
import com.zy.fee.roadpark.model.apimodel.APIM_NpNodeRecordList;
import com.zy.fee.roadpark.util.CheckPrinterStatus;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.LibraryHelper;
import com.zygk.library.util.ListUtils;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.Security;
import com.zygk.library.util.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class MainActivity extends BaseActivity {
  public static final String INTENT_UNREAD_NUM = "INTENT_UNREAD_NUM";
  public static final String INTENT_LOGIN_NAME = "INTENT_LOGIN_NAME";

  @BindView(R.id.ll_back) LinearLayout llBack;
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.tv_toll_collector) TextView tvTollCollector;
  @BindView(R.id.tv_toll_park) TextView tvTollPark;
  @BindView(R.id.rl_pot_list) RoundLinearLayout rlPotList;
  @BindView(R.id.tv_forensics) TextView tvForensics;
  @BindView(R.id.rl_forensics) RoundRelativeLayout rlForensics;
  @BindView(R.id.tv_collection) TextView tvCollection;
  @BindView(R.id.rl_collection) RoundRelativeLayout rlCollection;
  @BindView(R.id.rl_equipment_fault) RoundLinearLayout rlEquipmentFault;
  @BindView(R.id.tv_message) TextView tvMessage;
  @BindView(R.id.rl_message) RoundLinearLayout rlMessage;
  @BindView(R.id.tv_set) TextView tvSet;
  @BindView(R.id.rl_set) RoundLinearLayout rlSet;
  @BindView(R.id.rl_leave)
  RoundLinearLayout rlLeaveApply;
  @BindView(R.id.rl_sign_in)
  RoundLinearLayout rlSignIn;
  @BindView(R.id.tv_leave)
  TextView tvLeave;

  private Badge badge;
  private Badge badgeLeave; // 驶离申请-未处理消息
  private int unReadNum = -1;
  private M_Lot mLot;
  private List<M_Lot> lotList;
  private int unHandleNum = 50;

  @Override public void setContentView() {
    setContentView(R.layout.activity_main);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    registerReceiver(new String[] { Constants.BROADCAST_EXIT });
    unReadNum = getIntent().getIntExtra(INTENT_UNREAD_NUM, 0);
    lot_list();
  }

  private void initView() {
    llBack.setVisibility(View.GONE);
    lhTvTitle.setText("路内车位管理");

    tvTollCollector.setText("收费员：" + LibraryHelper.userManager().getUserInfo().getName());
    if (!PreferencesHelper.getSettingBoolean(PreferencesHelper.User.Key.USER_ALIAS)) {
      setAlias();
    }
  }

  private void initListener() {
    AppApplication.getPrinterImpl().connectPrinter(new IConnectCallback() {
      @Override public void onPrinterConnectSuccess() {
        AppApplication.isConnection = true;
        AppApplication.getPrinterImpl()
            .setAllParams(ParamsConstant.paperType(2), ParamsConstant.density(3));
        CheckPrinterStatus.getInstance(mContext).startCheck();
      }

      @Override public void onPrinterConnectFailed(int errorCode) {
        CheckPrinterStatus.getInstance(mContext).stopCheck();
        AppApplication.isConnection = false;
      }
    });
  }

  private void setAlias() {
    String alias = getIntent().getStringExtra(INTENT_LOGIN_NAME);

    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
  }

  private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
    @Override public void gotResult(int code, String alias, Set<String> tags) {
      String logs;
      switch (code) {
        case 0:
          // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
          PreferencesHelper.setSettingBoolean(PreferencesHelper.User.Key.USER_ALIAS, true);
          break;
        case 6002:
          // 延迟 60 秒来调用 Handler 设置别名
          mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
          break;
      }
    }
  };

  private static final int MSG_SET_ALIAS = 1001;
  private final Handler mHandler = new Handler() {
    @Override public void handleMessage(Message msg) {
      super.handleMessage(msg);
      switch (msg.what) {
        case MSG_SET_ALIAS:
          // 调用 JPush 接口来设置别名。
          JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null,
              mAliasCallback);
          break;
        default:
          Log.i("setAliasAndTags", "Unhandled msg - " + msg.what);
      }
    }
  };

  private void lot_list() {
    NpNodeLogic.lot_list(mContext, preferencesHelper.userManager().getUserID(),
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {

          }

          @Override public void onSucceed(Object obj) {
            APIM_LotList result = (APIM_LotList) obj;
            List<M_Lot> list = result.getLotList();
            lotList = new ArrayList<>();
            if (!ListUtils.isEmpty(list)) {
              for (M_Lot m_lot : list) {
                if (m_lot.getCountType() == 2 || m_lot.getCountType() == 3) {
                  lotList.add(m_lot);
                }
              }
            }
            showListDialog();
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {

          }
        });
  }

  private void showListDialog() {
    if (lotList.size() == 1) {
      mLot = lotList.get(0);
      tvTollPark.setText("当前停车场：" + mLot.getName());
      preferencesHelper.setSettingString(PreferencesHelper.User.Key.LOT_ID, mLot.getLotID());
      preferencesHelper.setSettingString(PreferencesHelper.User.Key.LOT_NAME, mLot.getName());
      AppApplication.instance().parkTelephone =
          (StringUtils.isBlank(mLot.getTelephone()) ? Constants.SERVICE_TELEPHONE
              : mLot.getTelephone());
      rlEquipmentFault.setVisibility(mLot.getCountType() == 2 ? View.VISIBLE : View.INVISIBLE);
      return;
    }
    CommonDialog.showLotListDialog(mContext, lotList, i -> {
      mLot = lotList.get(i);
      tvTollPark.setText("当前停车场：" + mLot.getName());
      preferencesHelper.setSettingString(PreferencesHelper.User.Key.LOT_ID, mLot.getLotID());
      preferencesHelper.setSettingString(PreferencesHelper.User.Key.LOT_NAME, mLot.getName());
      AppApplication.instance().parkTelephone =
          (StringUtils.isBlank(mLot.getTelephone()) ? Constants.SERVICE_TELEPHONE
              : mLot.getTelephone());
      rlEquipmentFault.setVisibility((mLot.getCountType() == 3 || mLot.getCountType() == 2) ? View.GONE : View.VISIBLE);
      rlLeaveApply.setVisibility(mLot.getCountType() == 3 ? View.VISIBLE : View.GONE);
      rlSignIn.setVisibility((mLot.getCountType() == 3 || mLot.getCountType() == 2) ? View.GONE : View.VISIBLE);

      if(rlLeaveApply.getVisibility() == View.VISIBLE) {
        npnode_record_apply_list();
      }
    });
  }

  @Override protected void onResume() {
    super.onResume();

    showBadge();

    login();

    if(rlLeaveApply.getVisibility() == View.VISIBLE && mLot != null) {
      npnode_record_apply_list();
    }
  }

  private void login() {
    CommonLogic.login(mContext,
        preferencesHelper.getSettingString(PreferencesHelper.User.Key.USER_NAME),
        Security.encryptByMD5(
            preferencesHelper.getSettingString(PreferencesHelper.User.Key.USER_PWD)),
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_AdminInfo result = (APIM_AdminInfo) obj;
            unReadNum = result.getUnReadNum();

            showBadge();
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void npnode_record_apply_list() {
    NpNodeRecordLogic.npnode_record_apply_list(mContext, 0, "", "",
      1, Constants.ROWS, new HttpRequest.HttpCallback() {
        @Override public void onStart() {
        }

        @Override public void onSucceed(Object obj) {
          APIM_NpNodeRecordList result = (APIM_NpNodeRecordList) obj;
          unHandleNum = result.getAllNum();
          showBadgeLeave();
        }

        @Override public void onFailed() {

        }

        @Override public void onFinish() {
        }
      });
  }

  private void showBadgeLeave() {
    if (unHandleNum > 0) {
      if (badgeLeave == null) {
        badgeLeave = new QBadgeView(mContext).bindTarget(tvLeave)
          .setBadgeNumber(unHandleNum)
          .setShowShadow(false);
      } else {
        badgeLeave.setBadgeNumber(unHandleNum);
      }
    } else {
      if (badgeLeave != null) badgeLeave.hide(true);
    }
  }

  private void showBadge() {
    if (unReadNum > 0) {
      if (badge == null) {
        badge = new QBadgeView(mContext).bindTarget(tvMessage)
            .setBadgeNumber(unReadNum)
            .setShowShadow(false);
      } else {
        badge.setBadgeNumber(unReadNum);
      }
    } else {
      if (badge != null) badge.hide(true);
    }
  }

  @OnClick({
      R.id.rl_pot_list, R.id.rl_forensics, R.id.rl_collection, R.id.rl_equipment_fault,
      R.id.rl_pay_back, R.id.rl_message, R.id.rl_set, R.id.rrl_user_info, R.id.rl_sign_in,
      R.id.rl_leave
  }) public void onViewClicked(View view) {
    Intent intent;
    switch (view.getId()) {
      case R.id.rl_pot_list:
        if (mLot.getCountType() == 2) {
          startActivity(new Intent(mContext, NbSpotListActivity.class));
        } else {
          startActivity(new Intent(mContext, NpSpotListActivity.class));
        }
        break;
      case R.id.rl_forensics:
        if (mLot.getCountType() == 2) {
          startActivity(new Intent(mContext, NbRegistrationPlateActivity.class));
        } else {
          startActivity(new Intent(mContext, NpRegistrationPlateActivity.class));
        }
        break;
      case R.id.rl_collection:
        if (mLot.getCountType() == 2) {
          startActivity(new Intent(mContext, NbReceivablesActivity.class));
        } else {
          startActivity(new Intent(mContext, PlateFindActivity.class));
        }
        break;
      case R.id.rl_equipment_fault:
        startActivity(new Intent(mContext, FaultDeclareActivity.class));
        break;
      case R.id.rl_pay_back:
        if (mLot.getCountType() == 2) {
          startActivity(new Intent(mContext, NbPayBackListActivity.class));
        } else {
          startActivity(new Intent(mContext, NpPayBackListActivity.class));
        }
        break;
      case R.id.rl_message:
        intent = new Intent(mContext, MessageListActivity.class);
        startActivity(intent);
        break;
      case R.id.rl_set:
        startActivity(new Intent(mContext, SettingActivity.class));
        break;
      case R.id.rrl_user_info:
        lot_list();
        break;
      case R.id.rl_sign_in:
        String strSignIn = "";
        try {
          strSignIn =
              "https://oa.nplusc.cn/api.php?m=opensso&ssotoken=" + LibraryHelper.userManager()
                  .getUserID() + "&backurl=" + URLEncoder.encode("index.php?d=we&m=ying&a=daka",
                  "UTF-8");
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }

        intent = new Intent(mContext, H5Activity.class);
        intent.putExtra(H5Activity.INTENT_URL, strSignIn);
        intent.putExtra(H5Activity.INTENT_TITLE, "考勤");
        startActivity(intent);
        break;
      case R.id.rl_leave:
        intent = new Intent(mContext, LeaveApplyActivity.class);
        startActivity(intent);
        break;
    }
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    super.handleReceiver(context, intent);
    if (intent == null || TextUtils.isEmpty(intent.getAction())) {
      return;
    }
    if (Constants.BROADCAST_EXIT.equals(intent.getAction())) {
      Intent i = new Intent();
      i.addCategory("android.intent.category.HOME");
      i.setAction("android.intent.action.MAIN");
      i.setClassName("com.android.launcher", "com.android.launcher3.Launcher");
      startActivity(i);
      finish();
    }
  }

  private long firstTime = 0;

  //@Override public void onBackPressed() {
  //  long secondTime = System.currentTimeMillis();
  //  if (secondTime - firstTime > 800) {
  //    ToastUtil.showMessage(mContext, "再按一次退出程序");
  //    firstTime = secondTime;
  //  } else {
  //    showNoCancelPd();
  //    System.exit(0);//否则退出程序
  //  }
  //}
  @Override protected void onDestroy() {
    AppApplication.getPrinterImpl().closeConnect();
    super.onDestroy();
  }
}